package jal4eclipse.ui.outline;

import jal4eclipse.jal.JALParser;
import jal4eclipse.jal.structure.JContainer;
import jal4eclipse.jal.structure.JElement;
import jal4eclipse.ui.editors.FileUtil;
import jal4eclipse.ui.editors.JALEditor;

import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.views.contentoutline.ContentOutlinePage;

public class JALOutline extends ContentOutlinePage {
	private JALEditor editor;

	public JALOutline(JALEditor editor) {
		this.editor = editor;

	}

	public void createControl(Composite parent) {
		super.createControl(parent);
		TreeViewer treeViewer = getTreeViewer();
		treeViewer.setContentProvider(new JALContentProvider());
		treeViewer.setLabelProvider(new JALLabelProvider());
		String content = editor.getDocument().get();
		treeViewer.setInput(JALParser.getFileStructure(content));
		treeViewer.expandAll();

		treeViewer.addSelectionChangedListener(new ISelectionChangedListener() {
			public void selectionChanged(SelectionChangedEvent event) {
				// if the selection is empty clear the label
				if (event.getSelection().isEmpty()) {
					return;
				}

				/*
				 * TODO Just for test ... need better impl here
				 */
				if (event.getSelection() instanceof IStructuredSelection) {
					IStructuredSelection selection = (IStructuredSelection) event
							.getSelection();
					Object elem = selection.getFirstElement();

					if (!(elem instanceof JContainer)) {

						JElement el = (JElement) elem;

						String name = el.getName();
						FileUtil.selectText(editor,name);
					}
				}
			}
		});

	}

	public TreeViewer getViewer() {
		return getTreeViewer();
	}

	public JALEditor getEditor() {
		return editor;
	}

	public void setEditor(JALEditor editor) {
		this.editor = editor;
	}

}
